﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;


namespace YXShop.TemplateAction
{
    public class Common
    {
        #region 前台调用模板
        /// <summary>
        /// 跟据模型名称查询模板路径获取模板内容
        /// </summary>
        /// <param name="FormerName">模型名称</param>
        /// <returns></returns>
        public static string YXShop_PageContent(string FormerName)
        {
            StringBuilder reStr = new StringBuilder();
            if (!string.IsNullOrEmpty(FormerName))
            {
                YXShop.BLL.SystemInfo.MouldInfo bll = new YXShop.BLL.SystemInfo.MouldInfo();
                YXShop.Model.SystemInfo.MouldInfo model = bll.GetModelName(FormerName);
                YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
                if (sp.IsOpenSite)
                {
                    HttpContext.Current.Response.Write(sp.ColecSiteDescription);
                    HttpContext.Current.Response.End();
                }
                if (model != null)
                {
                    string TemplatePath = sp.WebSiteTemplatePath + "/" + model.WebPagePath;
                    if (model.WebPagePath != string.Empty)
                    {
                        YXShop.TemplateAction.Template indexTemp = new YXShop.TemplateAction.Template(HttpContext.Current.Server.MapPath("~/") + TemplatePath);
                        indexTemp.GetHTML();
                        indexTemp.FrontReplaceLabels();

                        string getContent = indexTemp.FinallyContent;
                        if (Regex.Match(getContent, @"\</head\>[\s\S]*\<body", RegexOptions.IgnoreCase | RegexOptions.Compiled).Success)
                        {
                            getContent = Regex.Replace(getContent, "<body", "<body", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        }
                        reStr.Append(getContent);
                    }
                }
            }
            return reStr.ToString();
        }

        /// <summary>
        /// 跟据模板路径获取模板内容
        /// </summary>
        /// <param name="FormerName">模板路径</param>
        /// <returns></returns>
        public static string YXShop_PageContent2(string WebTemplatePath)
        {
            StringBuilder reStr = new StringBuilder();
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            if (sp.IsOpenSite)
            {
                HttpContext.Current.Response.Write(sp.ColecSiteDescription);
                HttpContext.Current.Response.End();
            }
            if (!string.IsNullOrEmpty(WebTemplatePath))
            {
                string TemplatePath = sp.WebSiteTemplatePath + "/" + WebTemplatePath;
                YXShop.TemplateAction.Template indexTemp = new YXShop.TemplateAction.Template(HttpContext.Current.Server.MapPath("~/") + TemplatePath);
                indexTemp.GetHTML();
                indexTemp.FrontReplaceLabels();

                string getContent = indexTemp.FinallyContent;
                if (Regex.Match(getContent, @"\</head\>[\s\S]*\<body", RegexOptions.IgnoreCase | RegexOptions.Compiled).Success)
                {
                    getContent = Regex.Replace(getContent, "<body", "<body", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                }
                reStr.Append(getContent);
            }
            return reStr.ToString();
        }
        #endregion

        #region 自定义文件名形成URL
        /// <summary>
        /// 自定义文件名形成URL
        /// </summary>
        /// <param name="pra"></param>
        /// <returns></returns>
        public static string URL(string pra)
        {
            string Query = HttpContext.Current.Request.Url.Query;
            string file = HttpContext.Current.Request.FilePath.ToString();
            string fileName = file.Substring(file.LastIndexOf("/") + 1, file.Length - (file.LastIndexOf("/") + 1));
            fileName = fileName.Substring(0, fileName.IndexOf('.'));
            string filePath = file.Substring(1, file.LastIndexOf("/"));
            if (!string.IsNullOrEmpty(Query))
            {
                Query = Query.Substring(1, Query.Length - 1);
                if (!string.IsNullOrEmpty(pra))
                {
                    string[] Parameter = pra.Split('=');
                    string[] pairs = Query.Split('&');
                    if (!string.IsNullOrEmpty(Parameter[0]))
                    {
                        if (Query.IndexOf(Parameter[0]) > -1)
                        {
                            for (int i = 0; i < pairs.Length; i++)
                            {
                                if (pairs[i].IndexOf(Parameter[0]) > -1)
                                {
                                    string oldParameter = pairs[i].ToString();
                                    Query = Query.Replace(oldParameter, pra);
                                }
                            }
                        }
                        else
                        {
                            Query = Query + ";" + pra;
                        }
                    }
                }
            }
            else
            {
                Query = pra;
            }
            string path =UrlStr(fileName, Query.Replace("&", ";"), filePath);
            return path;
        }
        /// <summary>
        /// 形成URL
        /// </summary>
        /// <param name="pra"></param>
        /// <returns></returns>
        public static string URL(string pra, string fileNames)
        {
            string Query = HttpContext.Current.Request.Url.Query;
            string file = HttpContext.Current.Request.FilePath.ToString();
            string fileName = file.Substring(file.LastIndexOf("/") + 1, file.Length - (file.LastIndexOf("/") + 1));
            fileName = fileName.Substring(0, fileName.IndexOf('.'));
            string filePath = file.Substring(1, file.LastIndexOf("/"));
            if (!string.IsNullOrEmpty(Query))
            {
                Query = Query.Substring(1, Query.Length - 1);
                if (!string.IsNullOrEmpty(pra))
                {
                    string[] Parameter = pra.Split('=');
                    string[] pairs = Query.Split('&');
                    if (!string.IsNullOrEmpty(Parameter[0]))
                    {
                        if (Query.IndexOf(Parameter[0]) > -1)
                        {
                            for (int i = 0; i < pairs.Length; i++)
                            {
                                if (pairs[i].IndexOf(Parameter[0]) > -1)
                                {
                                    string oldParameter = pairs[i].ToString();
                                    Query = Query.Replace(oldParameter, pra);
                                }
                            }
                        }
                        else
                        {
                            Query = Query + ";" + pra;
                        }
                    }
                }
            }
            else
            {
                Query = pra;
            }
            if (!string.IsNullOrEmpty(fileNames))
            {
                fileName = fileNames;
            }
            string filename=fileName;
            string urlparameter= Query.Replace("&", ";");
            string Path = filePath;
            string reURL = string.Empty;//返加值
            string Urlpar = string.Empty;//URL参数连接
            string Urlpars = string.Empty;//URL参数
            if (!string.IsNullOrEmpty(urlparameter))
            {
                string[] Par = urlparameter.Split(';');
                for (int i = 0; i < Par.Length; i++)
                {
                    if (Par[i].Trim() != string.Empty)
                    {
                        if (Par[i].IndexOf('=') > -1)
                        {
                            string[] ParVa = Par[i].Split('=');
                            Urlpar += "-" + ParVa[1];
                        }
                    }
                }
                Urlpars = urlparameter.Replace(";", "&");
            }
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            string DummyPath = "/"+Path;
            if (!sp.ISRewrite)
            {
                //动态
                if (!string.IsNullOrEmpty(Urlpars))
                {
                    reURL = DummyPath + filename + ".aspx?" + Urlpars;
                }
                else
                {
                    reURL = DummyPath + filename + ".aspx";
                }
            }
            else
            {
                //伪静态
                if (!string.IsNullOrEmpty(Urlpar))
                {
                    reURL = DummyPath + filename + Urlpar + sp.StaticPageFileType;
                }
                else
                {
                    reURL = DummyPath + filename + sp.StaticPageFileType;
                }
            }
            return reURL;
        }
        #endregion

        #region URL拼接
        /// <summary>
        /// url拼接
        /// </summary>
        /// <param name="Path">路径</param>
        /// <param name="filename">文件名</param>
        /// <param name="urlparameter">参数</param>
        /// <returns></returns>
        public static string UrlStr(string filename, string urlparameter, string Path)
        {
            string reURL = string.Empty;//返加值
            string Urlpar = string.Empty;//URL参数连接
            string Urlpars = string.Empty;//URL参数
            if (!string.IsNullOrEmpty(urlparameter))
            {
                string[] Par = urlparameter.Split(';');
                for (int i = 0; i < Par.Length; i++)
                {
                    if (Par[i].Trim() != string.Empty)
                    {
                        if (Par[i].IndexOf('=') > -1)
                        {
                            string[] ParVa = Par[i].Split('=');
                            Urlpar += "-" + ParVa[1];
                        }
                    }
                }
                Urlpars = urlparameter.Replace(";", "&");
            }
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            string DummyPath = sp.DummyPaht + Path;
            if (!sp.ISRewrite)
            {
                //动态
                if (!string.IsNullOrEmpty(Urlpars))
                {
                    reURL = DummyPath + filename + ".aspx?" + Urlpars;
                }
                else
                {
                    reURL = DummyPath + filename + ".aspx";
                }
            }
            else
            {
                //伪静态
                if (!string.IsNullOrEmpty(Urlpar))
                {
                    reURL = DummyPath + filename + Urlpar + sp.StaticPageFileType;
                }
                else
                {
                    reURL = DummyPath + filename + sp.StaticPageFileType;
                }
            }
            return reURL;
        }
        #endregion

        #region 查询省份(公用方法)
        public static string ProvinceStr(string field)
        {
            string Area = new YXShop.Common.Substation().ParentPath.Replace("0,","");
            string ReStr = string.Empty;
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            if (sp.IsCloseStation && Area != "0,")
            {

                if (Area != null && Area != "")
                {
                    if (Area == "0,1")
                    {
                        ReStr = "" + field + "= '" + Area + "'";
                    }
                    else
                    {
                        ReStr = "','+" + field + "+',' like '%," + Area + ",%'";
                    }
                }
            }
            return ReStr;
        }
        #endregion

        #region 资讯频道调用模板
        public static string InformationChannel(string FileType)
        {
            string reStr=string.Empty;
            string ChannelId = ChangeHope.WebPage.PageRequest.GetQueryString("q_ChannelId");
            YXShop.BLL.SystemInfo.ArticleChannel bll = new YXShop.BLL.SystemInfo.ArticleChannel();
            YXShop.Model.SystemInfo.ArticleChannel model = bll.GetModel(ChannelId);
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            if (model != null)
            {
                string ChannelType = model.Type;
                string TemplatePath = string.Empty;
                switch (ChannelType)
                {
                    case "1":
                        if (FileType == "default")
                        {
                            TemplatePath =  model.DefaultTemplate;
                        }
                        else if (FileType == "list")
                        {
                            TemplatePath = model.ListTemplate;
                        }
                        else if (FileType == "content")
                        {
                            TemplatePath = model.ContentTemplate;
                        }
                        break;
                    case "2":
                        TemplatePath = model.DefaultTemplate;
                        break;
                    case "3":
                        HttpContext.Current.Response.Redirect(model.ExternalLink);
                        break;
                    default:
                        break;
                }
                if (TemplatePath != string.Empty)
                {
                    TemplatePath = sp.WebSiteTemplatePath + "/" + TemplatePath;
                    YXShop.TemplateAction.Template indexTemp = new YXShop.TemplateAction.Template(HttpContext.Current.Server.MapPath("~/") + TemplatePath);
                    indexTemp.GetHTML();
                    indexTemp.FrontReplaceLabels();

                    string getContent = indexTemp.FinallyContent;
                    if (Regex.Match(getContent, @"\</head\>[\s\S]*\<body", RegexOptions.IgnoreCase | RegexOptions.Compiled).Success)
                    {
                        getContent = Regex.Replace(getContent, "<body", "<body", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    }
                    reStr=getContent;
                }

            }
            return reStr;
        }
        #endregion

        #region 跟据路径调用模板
        public static string StorePageContent(string path)
        {
            StringBuilder reStr = new StringBuilder();
            string storeId = ChangeHope.WebPage.PageRequest.GetString("StoreId");
            if (storeId == "")
            {
                reStr.Append("该店铺不存在!");
            }
            else
            {
                YXShop.BLL.Shop.Shop shopbll = new YXShop.BLL.Shop.Shop();
                YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
                if (!sp.IsOpenShops)
                {
                    HttpContext.Current.Response.Write(sp.CloseStoreDescription);
                    HttpContext.Current.Response.End();
                }
                YXShop.Model.Shop.Shop shopmodel = shopbll.GetModelById(Convert.ToInt32(storeId));
                if (shopmodel != null)
                {
                    YXShop.BLL.Shop.ShopColor scbll = new YXShop.BLL.Shop.ShopColor();
                    YXShop.Model.Shop.ShopColor scmodel = scbll.GetModel(Convert.ToInt32(shopmodel.Shopstyle));
                    if (scmodel != null)
                    {
                        string TemplatePath = scmodel.Templatepath + "/" + path;
                        YXShop.TemplateAction.Template indexTemp = new YXShop.TemplateAction.Template(HttpContext.Current.Server.MapPath("~/") + TemplatePath);
                        indexTemp.BackPath("", scmodel.Templatepath);
                        indexTemp.GetEidtLable(false);
                        indexTemp.GetHTML();
                        indexTemp.ReplaceLabels();

                        string getContent = indexTemp.FinallyContent;
                        if (Regex.Match(getContent, @"\</head\>[\s\S]*\<body", RegexOptions.IgnoreCase | RegexOptions.Compiled).Success)
                        {
                            getContent = Regex.Replace(getContent, "<body", "<body", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                        }
                        reStr.Append(getContent);
                    }

                }
            }
            return reStr.ToString();
        }
        #endregion

        #region 商品分类
        #region 商品分类查询判断(公用方法)
        public static string CodStr(string CID)
        {
            string reStr = CID;
            YXShop.BLL.Product.Productclass bll = new YXShop.BLL.Product.Productclass();
            string strWhere = CID;
            YXShop.Model.Product.Productclass model = bll.GetModelID(Convert.ToInt32(CID));
            if (model != null)
            {
                strWhere = model.Parentpath + "," + model.ID.ToString()+",";
                DataTable dt = bll.GetBlurList(strWhere);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    reStr += "," + dt.Rows[i]["cid"].ToString();
                }
                DataTable fdt = bll.GetFatherList(model.ID);
                for (int j = 0; j < fdt.Rows.Count; j++)
                {
                    reStr += "," + fdt.Rows[j]["cid"].ToString();
                }
            }
            return reStr;

        }
        #endregion
        #endregion

        #region 商品相册
        public static string ProductAlbum(string productID, string productName, string productImages, string productOriginal, bool IsSpecification, int SpeIndexof)
        {
            YXShop.Common.SysParameter sp = new YXShop.Common.SysParameter();
            StringBuilder shtml = new StringBuilder();
            YXShop.BLL.Product.ProductAlbum pgbll = new YXShop.BLL.Product.ProductAlbum();
            DataTable dt = null;
            if (IsSpecification)
            {
                DataTable dtSpe = pgbll.GetProAlbumAll(Convert.ToInt32(productID), SpeIndexof, 1);
                if (dtSpe.Rows.Count > 0)
                {
                    int aId = Convert.ToInt32(dtSpe.Rows[0]["id"].ToString());
                    dt = pgbll.GetProAlbumAll(0, aId, 1);
                    if (dt.Rows.Count > 0)
                    {
                        productImages = dt.Rows[0]["thumbnailaddress"].ToString();
                        productOriginal = dt.Rows[0]["originaladdress"].ToString();
                    }
                }
            }
            if (dt == null)
            {
                dt = pgbll.GetProAlbumAll(Convert.ToInt32(productID), -1, 0);
            }

            string albumURL = Common.UrlStr("product_album", "id=" + productID + "", "product/");
            shtml.Append("<div id=\"divProductAlbum\">");
            shtml.Append("<div id=\"Product_BigImage\" class=\"jqzoom\" onclick = \"window.open('" + albumURL + "')\">\r\n");
            shtml.Append("<img  onerror = \"this.src='" + sp.DummyPaht + "images/NaughtImages.gif'\"  alt=\"" + productName + "\" src=\"" + sp.DummyPaht + productImages + "\" width=\"349\" jqimg=\"" + sp.DummyPaht + productOriginal + "\"/>\r\n");

            shtml.Append("</div>\r\n");
            shtml.Append("<div id=\"Product_LittleImage\">\r\n");
            shtml.Append("<ul id=\"mycarousel\" class=\"jcarousel-skin-tango\">\r\n");
            shtml.Append("<li><img  onerror = \"this.src='" + sp.DummyPaht + "images/none_50.gif'\"  alt=\"" + productName + "\" src=\"" + sp.DummyPaht + productOriginal + "\" name=\"" + productImages + "\" id=\"" + productOriginal + "\"></li>\r\n");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                shtml.Append("<li><img  onerror = \"this.src='" + sp.DummyPaht + "images/none_50.gif'\"  alt=\""+ dt.Rows[i]["descriptoin"] + "\" src=\"" + sp.DummyPaht + dt.Rows[i]["thumbnailaddress"] + "\" name=\"" + dt.Rows[i]["originaladdress"] + "\" id=\"" + dt.Rows[i]["originaladdress"] + "\"></li>\r\n");
            }
            shtml.Append("</ul>\r\n");
            shtml.Append("</div>\r\n");
            string AlbumUrl = Common.UrlStr("product_album", "id=" + productID + "", "product/");
            shtml.Append("<div style='text-align:center;width:100%'><ul class='clickbigimage'><img alt=\"点此查看大图\" src=\"" + sp.DummyPaht + sp.WebSiteTemplatePath + "/images/zoom.gif\" />&nbsp; <a  class=\"link_1\"  onerror = \"this.src='" + sp.DummyPaht + sp.DummyPaht + "images/zoom.gif'\"    target=\"_blank\"  href=\"" + AlbumUrl + "\">查看大图</a></ul></div>");
            shtml.Append("</div>");
            return shtml.ToString();
        }
        #endregion
    }
}
